package com.example.blue_classic_plus.blueconnect;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Message;

import com.example.blue_classic_plus.StatusCode;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import io.flutter.plugin.common.EventChannel;

public class ClientThread extends Thread {
    //    private final BluetoothDevice device;
    private final BluetoothSocket socket;

    ///客户端连接成功
    public boolean connectSuccess = false;

    BluetoothAdapter bluetoothAdapter;

    Handler handler;

    public ClientThread(BluetoothDevice device, BluetoothAdapter adapter, UUID uuid, Handler handler) {
        this.handler = handler;
        BluetoothSocket tmp = null;
        //this.device = device;
        this.bluetoothAdapter = adapter;

        try {
            // 获取 BluetoothSocket
            tmp = device.createRfcommSocketToServiceRecord(uuid);
        } catch (Exception e) {
            //System.out.println("ClientThread:" + e);
        }
        socket = tmp;
    }

    public void run() {
        // 取消设备的发现，以节省资源
        bluetoothAdapter.cancelDiscovery();

        try {
            // 连接到服务端
            socket.connect();
            handleServerConnected();
            handleReceiveMessages();

        } catch (IOException connectException) {
            //System.out.println("ClientThread connectException:" + connectException);
            handleServerDisconnected();
        } finally {

        }

    }

    ///实时监听服务端的消息
    private void handleReceiveMessages() {
        byte[] buffer = new byte[1024];
        int bytes;

        while (socket.isConnected()) {
            try {
                // 读取服务端发送的消息
                bytes = socket.getInputStream().read(buffer);
                if (bytes > 0) {
                    String message = new String(buffer, 0, bytes);
                    processData(message);
                }
            } catch (IOException e) {
                ///连接断开
                System.out.println("receiveMessages error:" + e);
                handleServerDisconnected();
                break;
            }
        }
    }

    ///取消
    public void cancel() {
        try {
            if (socket != null) {
                socket.close();
            }
        } catch (IOException e) {
            System.out.println("ClientThread cancel:" + e);
        }
    }

    ///发送消息
    public void sendData(String data) {
        Thread sendThread = new Thread(() -> {
            try {
                OutputStream outputStream = socket.getOutputStream();
                outputStream.write(data.getBytes());
                outputStream.flush();
            } catch (IOException e) {
                System.out.println("消息发送失败:" + data);
            }
        });
        sendThread.start();
    }

    ///收到服务端的消息
    private void processData(String message) {
        //System.out.println("收到消息:" + message);

        Map<String, Object> map = new HashMap<>();
        map.put("msg", message);
        map.put("code", StatusCode.clientRecvMsg);
        sinkServerStatusToFlutter(map);
    }

    ///连接服务端蓝牙成功了
    private void handleServerConnected() {
        //System.out.println("连接成功了");
        connectSuccess = true;
        Map<String, Object> map = new HashMap<>();
        map.put("code", StatusCode.clientConnected);
        sinkServerStatusToFlutter(map);
    }

    ///与服务端蓝牙断开连接了
    private void handleServerDisconnected() {
        connectSuccess = false;
        cancel();
        System.out.println("连接断开了");

        Map<String, Object> map = new HashMap<>();
        map.put("code", StatusCode.clientDisConnected);
        sinkServerStatusToFlutter(map);
    }

    ///把客户端的状态告诉flutter
    private void sinkServerStatusToFlutter(Map<String, Object> map) {
        Message message = this.handler.obtainMessage(1,map);
        this.handler.sendMessage(message);
    }


}